package com.example.broadcast;

import android.app.PictureInPictureParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Rational;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class PictureInPictureActivity extends AppCompatActivity {

    private DesktopReceiver receiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_configuration_change);
        //注册接收器
        receiver = new DesktopReceiver();
        IntentFilter intentFilter=new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
        if(isInPictureInPictureMode)
        {
            Log.d("tang", "进入了画中画模式");
        }
        else {
            Log.d("tang", "退出了画中画模式");
        }
    }

    private class DesktopReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent!=null&&intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS))
            {
                String reason = intent.getStringExtra("reason");
                //有两种情况，一种是homekey，即按主菜单键回到主菜单，另一种是按任务栏键,就是最右边那个方形的键（recentapps）
                if(!TextUtils.isEmpty(reason)&&(reason.equals("homekey")||reason.equals("recentapps")))
                {
                    //Android8.0才开始有画中画模式
                    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O
                            &&!isInPictureInPictureMode())
                    {
                        //创建 画中画模式的参数构建器
                        PictureInPictureParams.Builder builder=new PictureInPictureParams.Builder();
                        Rational ratio=new Rational(10,5);
                        builder.setAspectRatio(ratio);
                        enterPictureInPictureMode(builder.build());
                    }
                }
            }
        }
    }
}
